package admin

import (
	"fmt"
	"strconv"
	"strings"
	"tcsc/sword"
	// "sword"
	"image"
	"image/draw"
	"image/gif"
	"image/jpeg"
	"image/png"
	"os"
	"path"
	"tcsc/models"

	"github.com/astaxie/beego"
	"github.com/boombuler/barcode"
	"github.com/boombuler/barcode/qr"
	"github.com/nfnt/resize"
)

var P_e = `解析form失败:`
var U_e = `更新失败:`
var I_e = `插入失败:`
var Tparse = `2006-01-02 15:04:05`

type BaseController struct {
	beego.Controller
	Qid string
	Gid string
}

func (c *BaseController) Prepare() {
	// c.SetSession("admin", "1")
	sess := c.GetSession("admin")
	if sess == nil {
		c.Ctx.Redirect(302, "/admin/login")
		return
	}
	c.Qid = fmt.Sprint(sess)
	url := strings.Split(c.Ctx.Request.RequestURI, "?")[0]
	url3 := strings.Split(url, "/")
	admin := models.Query(`select b.pathname,a.accountnumber,a.gid,d.nodes,a.permission from mt_systems_admin a left join mt_resources b on b.id=a.avatar 
	left join mt_systems_permissions d on a.permission=d.id where a.id=?`, c.Qid)[0]
	per := admin["nodes"].(string)
	c.Data["admin"] = admin
	c.Gid = fmt.Sprint(admin["gid"])
	c.Data["system"] = models.System
	c.Data["admin_gid"] = c.Gid
	c.Data["admin_uid"] = c.Qid
	var sql string
	if c.Gid == "0" {
		sql = "select id,name,iconfont,url from mt_nav_admin where status=1 and pid=0 and id in(" + per + ") order by sort desc"
	} else {
		sql = "select id,name,iconfont,url from mt_nav_admin where status=1 and pid=0 and isopen=1 and id in(" + per + ") order by sort desc"
	}
	top := models.Query(sql)
	for _, v := range top {
		turl := fmt.Sprint(v["url"])
		turls := strings.Split(turl, "/")
		if url3[1] != "search" {
			if turls[2] == url3[2] {
				v["activet"] = "1"
			} else {
				v["activet"] = "0"
			}
			var sql2 string
			if c.Gid == "0" {
				sql2 = "select id,name,url from mt_nav_admin where status=1 and id in(" + per + ") and pid=" + v["id"].(string) + " order by sort desc"
			} else {
				sql2 = "select id,name,url from mt_nav_admin where status=1 and id in(" + per + ") and isopen=1 and pid=" + v["id"].(string) + " order by sort desc"
			}
			if second := models.Query(sql2); second != nil {
				for _, s := range second {
					if turls[2] == url3[2] {
						surl := fmt.Sprint(s["url"])
						surls := strings.Split(surl, "/")
						if len(surls) > 3 {
							if surls[3] == url3[3] {
								s["actives"] = "1"
							} else {
								s["actives"] = "0"
							}
						} else {
							s["actives"] = "0"
						}
					} else {
						s["actives"] = "0"
					}
				}
				v["second"] = second
			}

		}
	}
	c.Data["top"] = top
	var p = 0
	var sql3 string
	if c.Gid == "0" {
		sql3 = `select name from mt_nav_admin where url='` + url + `' and id in(` + per + `)`
	} else {
		sql3 = `select name from mt_nav_admin where url='` + url + `' and id in(` + per + `) and isopen=1`
	}
	if title := models.Query(sql3); title != nil {
		c.Data["title"] = title[0]["name"]
		p = 1
	}
	if p == 0 {
		c.Ctx.Redirect(302, "/admin/permission")
	}
}

type Del struct {
	BaseController
}

func (c *Del) Get() {
	defer c.ServeJSON()
	id := c.GetString("id")
	table := c.GetString("table")
	err := models.Exec(`update ` + table + ` set status=0 where id=` + id)
	if err != nil {
		beego.Debug("删除"+table+"失败:", err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		r.Addtime = sword.Timeget()
		switch table {
		case "mt_member":
			r.Table = 9
		case "mt_member_vip":
			r.Table = 10
		case "mt_ad":
			r.Table = 11
		case "mt_keywords":
			r.Table = 12
		case "mt_shop":
			r.Table = 13
			if err := models.Exec(`update mt_product set status=0 where gid=` + id); err != nil {
				beego.Debug(err)
			}
			if err := models.Exec(`update mt_order_car set status=0 where gid=` + id); err != nil {
				beego.Debug(err)
			}
		case "mt_column":
			r.Table = 14
		case "mt_shop_add":
			r.Table = 15
		case "mt_product":
			r.Table = 16
			if err := models.Exec(`update mt_order_car set status=0 where pid=` + id); err != nil {
				beego.Debug(err)
			}
		case "mt_order":
			r.Table = 18
		case "mt_news":
			r.Table = 21
		case "mt_page":
			r.Table = 23
		case "mt_systems":
			r.Table = 26
		case "mt_systems_permissions":
			r.Table = 27
		case "mt_systems_admin":
			r.Table = 28
		case "mt_area":
			r.Table = 29
		case "mt_brand":
			r.Table = 34
			if err := models.Exec(`update mt_product set status=0 where bid=` + id); err != nil {
				beego.Debug(err)
			}
		case "mt_product_spec":
			r.Table = 35
		case "mt_product_parameter":
			r.Table = 36
		case "mt_product_attribute_column":
			r.Table = 37
		case "mt_product_attribute":
			r.Table = 38
		case "mt_coupon":
			if err := models.Exec(`update mt_member_coupon set status=0 where yid=` + id); err != nil {
				beego.Debug(err)
			}
			r.Table = 39
		case "mt_promote_add":
			r.Table = 58
		case "mt_active_gbuy":
			r.Table = 64
		case "mt_member_getcash":
			r.Table = 71
		case "mt_member_integral":
			r.Table = 73
		}
		r.Tid, _ = strconv.Atoi(id)
		r.Way = 4
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type Delete struct {
	BaseController
}

func (c *Delete) Get() {
	defer c.ServeJSON()
	id := c.GetString("id")
	table := c.GetString("table")
	err := models.Exec(`delete from ` + table + ` where id=` + id)
	if err != nil {
		beego.Debug("删除"+table+"失败:", err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		r.Addtime = sword.Timeget()
		switch table {
		case "mt_member":
			r.Table = 9
		case "mt_member_vip":
			r.Table = 10
		case "mt_ad":
			r.Table = 11
		case "mt_keywords":
			r.Table = 12
		case "mt_shop":
			r.Table = 13
		case "mt_column":
			r.Table = 14
		case "mt_shop_add":
			r.Table = 15
		case "mt_product":
			r.Table = 16
		case "mt_order":
			r.Table = 18
		case "mt_logistics":
			r.Table = 19
		case "mt_logistics_freight":
			r.Table = 20
		case "mt_news":
			r.Table = 21
		case "mt_page":
			r.Table = 23
		case "mt_active":
			r.Table = 25
		case "mt_systems":
			r.Table = 26
		case "mt_systems_permissions":
			r.Table = 27
		case "mt_systems_admin":
			r.Table = 28
		case "mt_area":
			r.Table = 29
		case "mt_brand":
			r.Table = 34
		case "mt_product_spec":
			r.Table = 35
		case "mt_product_parameter":
			r.Table = 36
		case "mt_product_attribute_column":
			r.Table = 37
		case "mt_product_attribute":
			r.Table = 38
		}
		r.Tid, _ = strconv.Atoi(id)
		r.Way = 4
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type Change struct {
	BaseController
}

func (c *Change) Get() {
	defer c.ServeJSON()
	js := make(map[string]interface{})
	c.Data["json"] = &js
	id := c.GetString("id")
	table := c.GetString("table")
	status := c.GetString("status")
	err := models.Exec(`update ` + table + ` set ` + status + `=abs(` + status + `-1) where id=` + id)
	var r models.Mt_systems_record
	var nowstatus string
	if err != nil {
		beego.Debug("更改状态"+table+"失败:", err)
		js["status"] = 0
	} else {
		js["status"] = 1
		info := models.Query(`select ` + status + ` from ` + table + ` where id=` + id)[0]
		nowstatus = info[status].(string)
		if c.Gid == "0" && table == "mt_product" && status == "censoring" {
			barcode := models.Query(`select barcode from mt_product where id=?`, id)[0]["barcode"]
			models.Exec(`update mt_product set censoring=? where barcode=?`, nowstatus, barcode)
		}
		if nowstatus == "0" {
			switch status {
			case "censoring":
				js["info"] = "下架"
				r.Way = 6
			case "recommend":
				js["info"] = "未推荐"
				r.Way = 8
			case "type":
				js["info"] = "不可见"
			case "paystate":
				js["info"] = "没有支付"
			case "status":
				js["info"] = "已隐藏"
			case "prohibit":
				js["info"] = "未禁用"
				r.Way = 78
			case "is_show":
				js["info"] = "已隐藏"
			}
		} else {
			switch status {
			case "censoring":
				js["info"] = "上架"
				r.Way = 5
			case "recommend":
				js["info"] = "已推荐"
				r.Way = 7
			case "type":
				js["info"] = "可见"
			case "paystate":
				js["info"] = "已经支付"
			case "status":
				js["info"] = "已显示"
			case "prohibit":
				js["info"] = "已禁用"
				r.Way = 79
			case "is_show":
				js["info"] = "已显示"
			}
		}
		r.Addtime = sword.Timeget()
		switch table {
		case "mt_member":
			r.Table = 9
		case "mt_member_vip":
			r.Table = 10
		case "mt_ad":
			r.Table = 11
		case "mt_keywords":
			r.Table = 12
		case "mt_shop":
			if status == "censoring" {
				if nowstatus == "0" {
					if err := models.Exec(`update mt_product set censoring=0 where gid=` + id); err != nil {
						beego.Debug(err)
					}
					if err := models.Exec(`update mt_order_car set status=0 where gid=` + id); err != nil {
						beego.Debug(err)
					}
				} else {
					if err := models.Exec(`update mt_product set censoring=1 where gid=` + id); err != nil {
						beego.Debug(err)
					}
				}
			}
			r.Table = 13
		case "mt_column":
			r.Table = 14
		case "mt_shop_add":
			r.Table = 15
		case "mt_product":
			if status == "censoring" && nowstatus == "0" {
				if err := models.Exec(`update mt_order_car set status=0 where pid=` + id); err != nil {
					beego.Debug(err)
				}
			}
			r.Table = 16
		case "mt_order":
			r.Table = 18
		case "mt_logistics":
			r.Table = 19
		case "mt_logistics_freight":
			r.Table = 20
		case "mt_news":
			r.Table = 21
		case "mt_page":
			r.Table = 23
		case "mt_active":
			r.Table = 25
		case "mt_systems":
			r.Table = 26
		case "mt_systems_permissions":
			r.Table = 27
		case "mt_systems_admin":
			r.Table = 28
		case "mt_area":
			r.Table = 29
		case "mt_brand":
			r.Table = 34
			if status == "censoring" {
				if nowstatus == "0" {
					if err := models.Exec(`update mt_product set censoring=0 where bid=` + id); err != nil {
						beego.Debug(err)
					}
				} else {
					if err := models.Exec(`update mt_product set censoring=1 where bid=` + id); err != nil {
						beego.Debug(err)
					}
				}
			}
			if status == "is_show" {
				if nowstatus == "0" {
					if err := models.Exec(`update mt_product set is_show=0 where bid=` + id); err != nil {
						beego.Debug(err)
					}
				} else {
					if err := models.Exec(`update mt_product set is_show=1 where bid=` + id); err != nil {
						beego.Debug(err)
					}
				}
			}
		case "mt_product_spec":
			r.Table = 35
		case "mt_product_parameter":
			r.Table = 36
		case "mt_product_attribute_column":
			r.Table = 37
		case "mt_product_attribute":
			r.Table = 38
		case "mt_coupon":
			if status == "censoring" && nowstatus == "0" {
				if err := models.Exec(`update mt_member_coupon set status=0 where yid=` + id); err != nil {
					beego.Debug(err)
				}
			}
			r.Table = 39
		case "mt_promote_add":
			r.Table = 58
		case "mt_active_gbuy":
			r.Table = 64
		case "mt_member_getcash":
			r.Table = 71
		case "mt_member_integral":
			r.Table = 73
		case "mt_active_sales":
			r.Table = 75
			pid := models.Query(`select pid from mt_active_sales where id=?`, id)[0]["pid"]
			go FixPrice(fmt.Sprint(pid))
		}
		r.Tid, _ = strconv.Atoi(id)
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
	c.Data["json"] = js
}

type Search struct {
	BaseController
}

func (c *Search) Post() {
	defer c.ServeJSON()
	t := c.GetString("t")
	name := c.GetString("name")
	sql := ""
	switch t {
	case "member":
		sql = `select id,monicker,mobile from mt_member where name like '%` + name + `%' or monicker like '%` + name + `%'`
	case "company":
		sql = `select id,name from mt_works_order_company where name like '%` + name + `%' or abbreviation like '%` + name + `%'`
	case "works":
		sql = `select id,title from mt_works where title like '%` + name + `%' or keywords like '%` + name + `%'`
	case "shop":
		sql = `select id,name from mt_shop where (name like '%` + name + `%' or sname like '%` + name + `%') and status=1`
	case "product":
		if c.Gid == "0" {
			sql = `select a.id,a.title from mt_product a left join mt_shop b on a.gid=b.id where (a.title like '%` + name + `%' or a.model like '%` + name + `%' or a.keywords like '%` + name + `%') and a.status=1 and (a.gid=0 or b.style=0)`
		} else {
			sql = `select id,title from mt_product where (title like '%` + name + `%' or model like '%` + name + `%' or keywords like '%` + name + `%') and status=1 and gid=` + c.Gid
		}
	}
	c.Data["json"] = models.Query(sql)
}

type Column struct {
	BaseController
}

func (c *Column) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	url := c.Ctx.Request.RequestURI
	urls := strings.Split(url, "/")
	var t string
	switch urls[2] {
	case "news":
		t = "n"
		c.Data["url"] = `/admin/news/column?`
		c.Data["A_url"] = `/admin/news/column_add`
		c.Data["E_url"] = `/admin/news/column_edit?`
	case "product":
		t = "p"
		c.Data["url"] = `/admin/product/column?`
		c.Data["A_url"] = `/admin/product/column_add`
		c.Data["E_url"] = `/admin/product/column_edit?`
	case "page":
		t = "d"
		c.Data["url"] = `/admin/page/column?`
		c.Data["A_url"] = `/admin/page/column_add`
		c.Data["E_url"] = `/admin/page/column_edit?`
	case "shop":
		t = "s"
		c.Data["url"] = `/admin/shop/column?`
		c.Data["A_url"] = `/admin/shop/column_add`
		c.Data["E_url"] = `/admin/shop/column_edit?`
	}
	c.Data["t"] = t
	sql := `select a.*,b.pathname,c.name as pname from mt_column a left join mt_resources b on a.img=b.id left join mt_column c on a.pid=c.id where a.pid=0 and a.status=1 and a.type='` + t + `' order by a.sort desc limit ` + page + `,` + num
	sql2 := `select count(a.id) as totals from mt_column a where a.status=1 and a.pid=0 and a.type='` + t + `'`
	info := models.Query(sql)
	for _, v := range info {
		if t == "p" {
			son := models.Query(`select a.*,b.pathname,c.name as pname from mt_column a left join mt_resources b on a.img=b.id left join mt_column c on a.pid=c.id 
			where a.pid=` + v["id"].(string) + ` and a.status=1 and a.type='` + t + `' order by a.sort desc`)
			for _, s := range son {
				s["son"] = models.Query(`select a.*,b.pathname,c.name as pname from mt_column a left join mt_resources b on a.img=b.id join mt_column c on a.pid=c.id 
			where a.pid=` + s["id"].(string) + ` and a.status=1 and a.type='` + t + `' order by a.sort desc`)
			}
			v["son"] = son
		}
	}
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	if c.Gid != "0" {
		c.TplName = "admin/public/shop-column.html"
	} else {
		c.TplName = "admin/public/column.html"
	}
}

type ColumnAE struct {
	BaseController
}

func (c *ColumnAE) Get() {
	url := c.Ctx.Request.RequestURI
	urls := strings.Split(url, "/")
	var t = ""
	c.Data["type"] = &t
	switch urls[2] {
	case "news":
		t = "n"
	case "product":
		t = "p"
	case "page":
		t = "d"
	case "shop":
		t = "s"
	}
	if t == "p" {
		cid := models.Query(`select id,name from mt_column where type='p' and pid=0 and status=1`)
		for _, v := range cid {
			v["son"] = models.Query(`select id,name from mt_column where type='p' and pid=` + v["id"].(string) + ` and status=1`)
		}
		c.Data["cid"] = cid
	}
	id := c.GetString("id")
	if id != "" {
		if info := models.Query(`select a.*,b.pathname from mt_column a left join mt_resources b on a.img=b.id where 
			a.type='` + t + `' and a.id=` + id + ` and a.gid=` + c.Gid); info != nil {
			c.Data["info"] = info[0]
		} else {
			c.Ctx.Redirect(302, strings.Split(url, "_")[0])
		}
	}
	c.TplName = "admin/public/column_ae.html"
}

func (c *ColumnAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	var r models.Mt_systems_record
	id := input.Get("id")
	gid := c.Gid
	input.Set("gid", gid)
	if id == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
	}
	var level = "1"
	cid := input.Get("pid")
	beego.Debug(input.Get("pid"))
	beego.Debug(cid)
	if cid != "0" {
		plevel := models.Query(`select level from mt_column where id=` + cid)
		if plevel != nil {
			level = fmt.Sprint(plevel[0]["level"])
		} else {
			level = "0"
		}
		level = sword.Sum(level, "1")
	}
	input.Set("level", level)
	if res, err := models.Save("mt_column", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		r.Tid = int(res)
		if id == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 14
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
		c.Data["json"] = 1
	}
}

type ColumnChange struct {
	BaseController
}

func (c *ColumnChange) Post() {
	defer c.ServeJSON()
	var js = make(map[string]interface{})
	c.Data["json"] = &js
	id := c.GetString("id")
	cid := c.GetString("cid")
	status := c.GetString("status")
	err := models.Exec(`update mt_product set ` + status + `=abs(` + status + `-1) where id=` + id)
	var r models.Mt_systems_record
	if err != nil {
		beego.Debug("更改状态失败:", err)
		js["status"] = 0
	} else {
		js["status"] = 1
		if err := models.Exec(`update mt_product set cid=` + cid + ` where id=` + id); err != nil {
			beego.Debug(err)
		}
		js["info"] = models.Query(`select name from mt_column where id =` + cid)[0]["name"].(string)
		r.Way = 3
		r.Table = 16
		r.Addtime = sword.Timeget()
		r.Tid, _ = strconv.Atoi(id)
		beego.Debug(strconv.Atoi(c.Qid))
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type ColumnGet struct {
	beego.Controller
}

func (c *ColumnGet) Get() {
	defer c.ServeJSON()
	var js = make(map[string]interface{})
	c.Data["json"] = &js
	id := c.GetString("id")
	level := models.Query(`select level from mt_column where id=` + id)[0]["level"]
	if fmt.Sprint(level) == "1" {
		column2 := models.Query(`select id,name from mt_column where status=1 and pid=` + id)
		if len(column2) > 0 {
			js["column3"] = models.Query(`select id,name from mt_column where status=1 and pid=` + column2[0]["id"].(string))
		}
		for _, v := range column2 {
			attribute := models.Query(`select id,name from mt_product_attribute_column where status=1 and cid=` + v["id"].(string) + ` order by sort desc`)
			for _, a := range attribute {
				a["attribute"] = models.Query(`select id,name from mt_product_attribute where status=1 and cid=` + a["id"].(string) + ` order by sort desc`)
			}
			v["acolumn"] = attribute
		}
		js["column2"] = column2
	} else {
		js["column3"] = models.Query(`select id,name from mt_column where status=1 and pid=` + id)
	}
}

type ColumnGetG struct {
	beego.Controller
}

func (c *ColumnGetG) Get() {
	defer c.ServeJSON()
	gid := c.GetString("gid")
	c.Data["json"] = models.Query(`select id,name from mt_column where status=1 and pid=0 and gid=` + gid)
}

type AreaGet struct {
	beego.Controller
}

func (c *AreaGet) Get() {
	defer c.ServeJSON()
	code := c.GetString("code")
	res := models.Query(`select a.* from mt_area a left join mt_area b on a.pid=b.id where b.code=` + code)
	for k, v := range res {
		if k == 0 {
			v["son"] = models.Query(`select a.* from mt_area a left join mt_area b on a.pid=b.id where b.code=` + v["code"].(string))
		}
	}
	c.Data["json"] = res
}

type Logout struct {
	beego.Controller
}

func (c *Logout) Get() {
	c.DelSession("admin")
	c.Ctx.Redirect(302, "/admin/login")
}

type Qrcode struct {
	beego.Controller
}

func (c *Qrcode) Get() {
	defer c.ServeJSON()
	js := make(map[string]interface{})
	c.Data["json"] = &js
	js["status"] = 0
	id := c.GetString("id")
	product := models.Query(`select b.pathname from mt_product a 
		left join mt_resources b on a.img=b.id where a.id=?`, id)
	if product == nil {
		return
	}
	pathname := strings.Split(product[0]["pathname"].(string), ".com")[1]
	pathname = strings.Split(pathname, "?")[0]
	beego.Debug(pathname)
	ext := path.Ext(strings.ToLower(pathname))
	beego.Debug(ext)
	imgf, _ := os.Open(strings.TrimLeft(pathname, "/"))
	beego.Debug(strings.TrimLeft(pathname, "/"))
	defer imgf.Close()
	var img image.Image
	if ext == ".jpg" || ext == ".jpeg" {
		img, _ = jpeg.Decode(imgf)
	} else if ext == ".png" {
		img, _ = png.Decode(imgf)
	}
	qrb, _ := qr.Encode("https://www.tongcaigou.com/mobile/column/product_content?id="+id, qr.M, qr.Auto)
	qrb, _ = barcode.Scale(qrb, 200, 200)
	offset := image.Pt(75, 75)
	b := qrb.Bounds()
	m := image.NewRGBA(b)
	s := resize.Resize(50, 50, img, resize.Lanczos3)
	draw.Draw(m, b, qrb, image.ZP, draw.Src)
	draw.Draw(m, s.Bounds().Add(offset), s, image.ZP, draw.Over)
	os.MkdirAll("static/qr", 0777)
	pathname = "static/qr/prQr" + id + ".jpg"
	imgw, _ := os.Create(pathname)
	jpeg.Encode(imgw, m, nil)
	defer imgw.Close()
	js["status"] = 1
	js["pathname"] = pathname
}

type Attachment struct {
	beego.Controller
}

func (c *Attachment) Get() {
	pathname := c.GetString("pathname")
	c.Ctx.Output.Download(pathname)
}

type ProImgWatermark struct {
	beego.Controller
}

func (c *ProImgWatermark) Get() {
	return
	defer c.ServeJSON()
	js := make(map[string]interface{})
	c.Data["json"] = &js
	js["status"] = 0
	watermarkf, _ := os.Open("static/img/tc-watermark.png")
	watermark, _ := png.Decode(watermarkf)
	defer watermarkf.Close()
	pros := models.Query(`select id,image,content from mt_product where status=1 and censoring=1`)
	for _, v := range pros {
		var imgs []string
		var imgs1 []string
		image := fmt.Sprint(v["image"])
		if image != "" {
			pathnames := models.Query(`select pathname from mt_resources where id in(` + image + `)`)
			if pathnames != nil {
				for _, p := range pathnames {
					imgs = append(imgs, fmt.Sprint(p["pathname"]))
				}
			}
		}
		content := fmt.Sprint(v["content"])
		if content != "" {
			imgs1 = sword.UeditorImg(content)
		}
		imgs = append(imgs, imgs1...)
		var images []string
		for _, i := range imgs {
			pathname := strings.TrimLeft(i, "/")
			ext := path.Ext(pathname)
			filename := strings.TrimRight(pathname, ext) + "-source" + ext
			isExists, _ := PathExists(filename)
			if !isExists {
				images = append(images, i)
			}
		}
		if len(images) != 0 {
			ProImgWatermarkFile(images, watermark)
			beego.Debug(v["id"])
		}
	}
	js["status"] = 1
}

func SetProImgWatermark(pid string) {
	watermarkf, _ := os.Open("static/img/tc-watermark.png")
	watermark, _ := png.Decode(watermarkf)
	defer watermarkf.Close()
	pros := models.Query(`select image,content from mt_product where id=?`, pid)
	for _, v := range pros {
		var imgs []string
		var imgs1 []string
		image := fmt.Sprint(v["image"])
		if image != "" {
			pathnames := models.Query(`select pathname from mt_resources where id in(` + image + `)`)
			if pathnames != nil {
				for _, p := range pathnames {
					imgs = append(imgs, fmt.Sprint(p["pathname"]))
				}
			}
		}
		content := fmt.Sprint(v["content"])
		if content != "" {
			imgs1 = sword.UeditorImg(content)
		}
		imgs = append(imgs, imgs1...)
		var images []string
		for _, i := range imgs {
			pathname := strings.TrimLeft(i, "/")
			ext := path.Ext(pathname)
			filename := strings.TrimRight(pathname, ext) + "-source" + ext
			isExists, _ := PathExists(filename)
			if !isExists {
				images = append(images, i)
			}
		}
		if len(images) != 0 {
			ProImgWatermarkFile(images, watermark)
		}
	}
}

func ProImgWatermarkFile(paths []string, watermark image.Image) {
	for _, v := range paths {
		pathname := strings.TrimLeft(v, "/")
		file, err := os.Open(pathname)
		if err != nil {
			continue
		}
		ext := strings.ToLower(path.Ext(pathname))
		var img image.Image
		if ext == ".jpg" || ext == ".jpeg" {
			img, err = jpeg.Decode(file)
		} else if ext == ".png" {
			img, err = png.Decode(file)
		} else if ext == ".gif" {
			img, err = gif.Decode(file)
		} else {
			continue
		}
		if err != nil {
			beego.Debug(err)
			continue
		}
		b := img.Bounds()
		width := b.Dx()
		height := b.Dy()
		watermarkw := width / 2
		offsetLeft := width / 4

		reduce := resize.Resize(uint(watermarkw), 0, watermark, resize.Lanczos3)
		reduceh := reduce.Bounds().Dy()
		offsetTop := (height - reduceh) / 2

		offset := image.Pt(offsetLeft, offsetTop)
		m := image.NewRGBA(b)

		draw.Draw(m, b, img, image.ZP, draw.Src)
		draw.Draw(m, reduce.Bounds().Add(offset), reduce, image.ZP, draw.Over)

		newFilename := strings.TrimRight(pathname, path.Ext(pathname)) + "-source" + path.Ext(pathname)
		filew, _ := os.Create(newFilename)
		file.Close()
		file, _ = os.Create(pathname)
		if ext == ".jpg" || ext == ".jpeg" {
			jpeg.Encode(filew, img, nil)
			jpeg.Encode(file, m, nil)
		} else if ext == ".png" {
			png.Encode(filew, img)
			png.Encode(file, m)
		} else if ext == ".gif" {
			gif.Encode(filew, img, nil)
			gif.Encode(file, m, nil)
		}
		filew.Close()
		file.Close()
	}
}

// type SourceImg struct {
// 	BaseController
// }

// func (c *SourceImg) Get() {
// 	pros := models.Query(`select image,content from mt_product
// 		where gid in (select id from mt_shop where censoring=1 and status=1 and style=1) and status=1 and censoring=1`)
// 	for _, v := range pros {
// 		var imgs []string
// 		var imgs1 []string
// 		image := fmt.Sprint(v["image"])
// 		if image != "" {
// 			img = models.Query(`select pathname from mt_resources where id in (`+image+`)`)
// 			if img != nil {
// 				for _, v := range img {
// 					imgs = append(imgs, fmt.Sprint(v["pathname"]))
// 				}
// 			}
// 		}
// 		if fmt.Sprint(v["content"]) != "" {
// 			imgs1 = sword.UeditorImg(content)
// 		}
// 		imgs = append(imgs, imgs1...)
// 		for _, v := range imgs {
// 			pathname := strings.TrimLeft(v, "/")
// 			ext := path.Ext(pathname)
// 			source := strings.TrimRight(source, ext) + "-source" + ext
// 			isExists, _ := PathExists(source)
// 			if !isExists {
// 				source := pathname + "-source" + strings.ToLower(ext)
// 				isExists, _ := PathExists(source)
// 				if !isExists {
// 					source = pathname
// 				}
// 			}
// 			if source != pathname {
// 				sourceFile, err := os.Open(source)
// 				if err != nil {
// 					continue
// 				}
// 				file, err := os.Create(pathname)
// 				if err != nil {
// 					continue
// 				}
// 				io.Copy(sourceFile, file)

// 			}
// 		}
// 	}
// }

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

// type Test struct {
// 	beego.Controller
// }

// func (c *Test) Get() {
// 	c.ServeJSON()
// }

// 給統閃配提供publictoken接口
type WxToken struct {
	beego.Controller
}

func (c *WxToken) Get() {
	access_token := models.GetAccessToken("")
	c.Data["json"] = access_token
	c.ServeJSON()
}
